import 'package:flutter/material.dart';
import 'package:flutter_bugly_plugin/lib.dart';

import 'update_dialog.dart';

void main() => FlutterBugly.postCatchException(
      () => runApp(MyApp()),
      debugUpload: true,
      onCatchCallback: (msg, detail) {
        print("捕获异常回调：" + msg);
        print(detail);
      },
    );

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _platformVersion = 'Unknown';
  GlobalKey<UpdateDialogState> _dialogKey = new GlobalKey();

  @override
  void initState() {
    super.initState();
    FlutterBugly.init(
      androidAppId: "8b841196c7",
      channel: "debug_channel",
      customUpgrade: false,
      customExtraDataSize: 10,
    ).then((_result) {
      print("bugly初始化结果：${_result.message}");

      setState(() {
        _platformVersion = _result.message;
        print(_result.appId);
      });
    });

    ///TODO 当配置 customUpgrade=true 时候，这里可以接收自定义升级
    FlutterBugly.onCheckUpgrade.listen((_upgradeInfo) {
      _showUpdateDialog(_upgradeInfo.newFeature, _upgradeInfo.apkUrl, _upgradeInfo.upgradeType == 2);
    });

    FlutterBugly.setUserId("18672175700");
    FlutterBugly.putUserData(key: "putUserData-key", value: "putUserData-value");
    FlutterBugly.setUserTag(9999);

    _putCustomData();
  }

  void _putCustomData() async {
    for (int i = 1; i < 100; i++) {
      await Future.delayed(Duration(milliseconds: 50));
      await FlutterBugly.putCustomExtraData(key: 'xxx-key$i', value: 'xxx-value$i');
    }
  }

  @override
  void dispose() {
    FlutterBugly.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter bugly app'),
      ),
      body: Column(
        children: [
          Text('init result: $_platformVersion\n'),
          RaisedButton(
            onPressed: () {
              _checkUpgrade();
            },
            child: Text('检查更新'),
          ),
          RaisedButton(
            onPressed: () {
              throw "手动产生Flutter异常，哈哈哈";
            },
            child: Text('点击产生Flutter异常'),
          ),
        ],
      ),
    );
  }

  void _showUpdateDialog(String version, String url, bool isForceUpgrade) {
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (_) => _buildDialog(version, url, isForceUpgrade),
    );
  }

  void _checkUpgrade() {
    print("获取更新中。。。");
    FlutterBugly.checkUpgrade();
  }

  Widget _buildDialog(String version, String url, bool isForceUpgrade) {
    return WillPopScope(
        onWillPop: () async => isForceUpgrade,
        child: UpdateDialog(
          key: _dialogKey,
          version: version,
          onClickWhenDownload: (_msg) {
            //提示不要重复下载
          },
          onClickWhenNotDownload: () {
            //下载apk，完成后打开apk文件，建议使用dio+open_file插件
          },
        ));
  }

  //dio可以监听下载进度，调用此方法
  void _updateProgress(_progress) {
    setState(() {
      _dialogKey.currentState.progress = _progress;
    });
  }
}
